<template>
  <div class="user" v-loading="loading">
    <el-card shadow="never">
      <el-form ref="searchFormRef" :inline="true" :model="searchData">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="searchData.username" placeholder="请输入" />
        </el-form-item>
        <el-form-item prop="phone" label="手机号">
          <el-input v-model="searchData.phone" placeholder="请输入" />
        </el-form-item>
        <el-form-item>
          <el-button type="primary" icon="Search" :disabled="!searchData.username && !searchData.phone " @click="handleSearch">
            查询
          </el-button>
          <el-button icon="Refresh" @click="resetSearch">
            重置
          </el-button>
        </el-form-item>
      </el-form>
    </el-card>
    <el-card shadow="never" style="margin-top: 10px;">
      <div class="card_button">
        <div>
          <el-button type="primary" icon="Plus" @click="handleEdit_Add">添加用户</el-button>
          <el-button type="danger" icon="Delete" @click="handleDeleteAll">批量删除</el-button>
        </div>
        <div>
          <el-button icon="Operation" circle plain  />
          <el-button icon="Download" circle plain />
        </div>
      </div>
      <div class="card_table">
        <el-table :data="UserList" @selection-change="selectchange" style="width: 100%" max-height="600px">
          <el-table-column width="100" align="center" type="selection" />
          <el-table-column label="序号" width="100" align="center" type="index" />
          <el-table-column prop="username" label="用户名" align="center" />
          <el-table-column prop="name" label="用户昵称" align="center" />
          <el-table-column prop="phone" label="手机号码" align="center" />
          <el-table-column prop="roleName" label="用户角色" align="center" show-overflow-tooltip />
          <el-table-column prop="createTime" label="创建时间" align="center" show-overflow-tooltip />
          <el-table-column prop="updateTime" label="更新时间" align="center" show-overflow-tooltip />
          <el-table-column fixed="right" min-width="240" label="操作" align="center">
            <template #default="scope">
              <el-button type="primary" text bg size="small" @click="handleUser(scope.row)">
                分配角色
              </el-button>
              <el-button type="primary" text bg size="small" @click="handleEdit_Add(scope.row)">
                编辑
              </el-button>
              <el-button type="danger" text bg size="small" @click="handleDelete(scope.row)" >
                删除
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
      <div class="card_page">
        <Pagination :currentPage="currentPage" :total="total" :pageSize="pageSize" @CurrentChange="CurrentChange"
          @SizeChange="SizeChange"></Pagination>
      </div>
    </el-card>

    <el-dialog v-model="dialogVisible" :title="formData.id ? '编辑用户' : '添加用户'" @close="resetForm">
      <el-form ref="formRef" :model="formData" :rules="formRules" label-width="100px" label-position="left">
        <el-form-item prop="username" label="用户名">
          <el-input v-model="formData.username" placeholder="请输入用户名..." />
        </el-form-item>
        <el-form-item prop="name" label="用户昵称">
          <el-input v-model="formData.name" placeholder="请输入用户昵称..." />
        </el-form-item>
        <el-form-item prop="password" label="用户密码" v-if="!formData.id">
          <el-input v-model="formData.password" placeholder="请输入用户秘密..." />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="resetForm">
          取消
        </el-button>
        <el-button type="primary" :loading="loading" @click="handleCreateOrUpdate">
          确认
        </el-button>
      </template>
    </el-dialog>

    <el-drawer v-model="drawer" title="角色职位分配">
      <el-form :model="formData" label-width="auto">
        <el-form-item label="用户名">
          <el-input v-model="formData.username" disabled />
        </el-form-item>
        <el-form-item label="分配职位">
          <Checkbox v-model:roleList="roleList" v-model:assignRoles="assignRoles" @chekedallRole="emitvalues">
          </Checkbox>
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button type="primary" @click="dearUpdate" :loading="Btnloading">确定</el-button>
      </template>
    </el-drawer>
  </div>
</template>

<script setup lang="ts" name="User">
import { onMounted, reactive, ref } from 'vue';
import { UserListAPI, AddUserAPI, updateUserAPI, AllUserRoleAPI, SetRoleAPI, DeleteUserAPI, AllDeleteUserAPI } from "@/apis/acl/user/index"
import Checkbox from './Checkbox.vue'
const loading = ref(false)
const Btnloading = ref(false)
const dialogVisible = ref(false)
const drawer = ref(false)
const UserList = ref([])  //用户数据
let roleList = ref([])    //所有权限
let assignRoles = ref([]) //拥有权限

const formRef = ref()
// 对话框表单
const formData = reactive({
  id: '',
  username: '',
  name: '',
  password: ''
})
// 对话框表单规则
const formRules = reactive({
  username: [
    { required: true, message: '请输入用户名...', trigger: 'blur' },
    { min: 1, max: 8, message: '长度为1-8位', trigger: 'blur' },
  ],
  name: [
    { required: true, message: '请输入用户昵称...', trigger: 'blur' },
    { min: 1, max: 8, message: '长度为1-8位', trigger: 'blur' },
  ],
  password: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 6, max: 16, message: "长度在 6 到 16 个字符", trigger: "blur" }
  ]
})
//  搜索
const searchFormRef = ref()
const searchData = reactive({
  username: '',
  phone: ''
})



// 搜索
const handleSearch = () => {
    getUserList()
}
const resetSearch = () => {
    searchData.phone=''
    searchData.username=''
    getUserList()
}


//#region 分页方法
//  分页数据
let currentPage = ref(1)
const total = ref(10)
const pageSize = ref(5)
// 当前页数改变
const CurrentChange = (value: number) => {
  currentPage.value = value
  getUserList()
}
// 当前页面条数改变
const SizeChange = (value: number) => {
  pageSize.value = value
  getUserList()
}
//#endregion

//#region 获取信息 查
const getUserList = () => {
  loading.value = true
  UserListAPI(currentPage.value, pageSize.value,searchData.username).then((res) => {
    // console.log(res);
    UserList.value = res.data.records
    total.value = res.data.total
  }).catch(() => {
    UserList.value = []
  }).finally(() => {
    loading.value = false
  })
}
//#endregion

//#region 删
const DeleteList = ref<any>([])
const handleDelete = async (row: any) => {
  try {
    await ElMessageBox.confirm(
      `确认删除:${row.name}吗?`,
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    DeleteUserAPI(row.id).then((res) => {
      // console.log(res);
      getUserList()
      ElMessage.warning('不知道接口是不是出问题了')
    })
  } catch (error) {
    ElMessage.error('已取消删除')
  }
}

// 批量删除
const handleDeleteAll = async () => {
  try {
    await ElMessageBox.confirm(
      `确认要删除吗?`,
      '提示',
      {
        confirmButtonText: '确认',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    AllDeleteUserAPI(DeleteList.value).then((res) => {
      console.log(res);
      getUserList()
      ElMessage.warning('不知道接口是不是出问题了')
    })
  } catch (error) {
    ElMessage.error('已取消删除')
  }
}

// 表单多选数据删除
const selectchange = (newSelection: any[]) => {
  DeleteList.value = newSelection.map((item) => item.id)
}
//#endregion

//#region 增改
const handleEdit_Add = (row: any) => {
  if (row) {
    formData.id = row.id
    formData.username = row.username
    formData.name = row.name
  }
  dialogVisible.value = true
}
//#endregion

// 分配角色
const handleUser = (row: any) => {
  formData.username = row.username
  formData.id = row.id
  AllUserRoleAPI(row.id).then((res) => {
    // console.log(res);
    roleList.value = res.data.allRolesList
    assignRoles.value = res.data.assignRoles
    drawer.value = true
  })
}



// 多选框数据
let data = ref({})
/**
 * @param val 多选框子组件传递的数据
 * */
const emitvalues = (val: any) => {
  // console.log(val);
  data.value = {
    userId: formData.id,
    roleIdList: val.map((item: { id: number; }) => {
      return item.id
    })
  }
}


// 提交权限
const dearUpdate = () => {
  Btnloading.value = true
  SetRoleAPI(data.value).then((res) => {
    // console.log(res); 成功
    ElMessage.success('分配成功')
    drawer.value = false
    getUserList()
  }).catch((error) => {
    // console.log(error);
    ElMessage.error('分配失败')
  }).finally(() => {
    Btnloading.value = false
  })
  // console.log(data.value)
}


// const userss=ref({
//   username: 'abc',
//   name: 'abc',
//   password: '123456'
// })

//  onMounted(()=>{
//   AddUserAPI(userss.value).then((res)=>{
//         console.log('添加',res);
//   })
//  })
// 提交  编辑接口有问题201
const handleCreateOrUpdate = async () => {
  if (!formRef.value) return
  await formRef.value.validate((valid: any, fields: any) => {
    if (valid) {
      let api = formData.id ? updateUserAPI : AddUserAPI
      api(formData).then((res:any) => {
        //  console.log(res);  //201接口
        ElMessage.warning(formData.id ? '编辑成功'+res.code : '添加成功'+res.code)
        formData.id ? currentPage.value : currentPage.value = 1
        getUserList()
      }).catch(() => {
        ElMessage.error(formData.id ? '编辑失败' : '添加失败，请重新添加')
      }).finally(() => {
        dialogVisible.value = false
      })
    } else {
      ElMessage.error('表单验证未通过')
    }
  })
}

// 清除规则、
const resetForm = () => {
  if (!formRef.value) return
  dialogVisible.value = false
  formRef.value.resetFields()
}


// 获取数据
getUserList()
</script>

<style lang="scss" scoped>
.user {
  .card_button {
    display: flex;
    justify-content: space-between;
    align-content: center;
  }

  .card_page {
    display: flex;
    justify-content: space-around;
    align-content: center;
    margin-top: 10px;
  }
}
</style>
